package com.dk.action;

import com.alibaba.fastjson.JSON;
import com.dk.domain.ActionEntity;
import com.dk.domain.action.ExtractParameterEntity;
import com.dk.domain.action.SqlActionBodyEntity;
import com.dk.enumerate.DkRuleEnum;
import com.dk.testcase.BaseCase;
import com.dk.util.config.ReadConfig;
import com.dk.util.jdbc.JdbcUtil;
import com.dk.util.log.Log;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * Sql插入实现策略
 */
public class SqlInsertHandler implements ActionStrategy {
    /**
     * Sql插入
     * @param actionEntity 动作对象
     */
    @Override
    public void Action(ActionEntity actionEntity) {
        //获取动作主体内容
        String actionBody = actionEntity.getActionBody();
        //将动作主体内容转换为sql执行主体对象
        SqlActionBodyEntity sqlActionBodyEntity = JSON.parseObject(actionBody, SqlActionBodyEntity.class);

        //通过数据库名称获取到数据库信息
        Map<String,String> dbConfig = BaseCase.dbConfigMap.get(sqlActionBodyEntity.getDb());
        //获取jdbc连接对象
        Connection conn = JdbcUtil.getConnection(ReadConfig.JDBC_DRIVER,
                dbConfig.get(DkRuleEnum.DB_URL.getValue()),
                dbConfig.get(DkRuleEnum.DB_USER.getValue()),
                dbConfig.get(DkRuleEnum.DB_PWD.getValue()));
        Log.info("---【数据库插入】:开始执行插入操作，插入sql:"+sqlActionBodyEntity.getSql()+";");
        //执行sql插入获取插入成功结果
        int winNum = JdbcUtil.insert(conn,sqlActionBodyEntity.getSql());
        if(winNum==0){
            Log.error("---【error】:插入数据失败，请检查数据,ActionNum:"+actionEntity.getActionNum()+";执行sql:"+sqlActionBodyEntity.getSql()+";");
        }else{
            Log.info("---【数据库插入】:插入成功，成功条数:"+winNum+"条;");
        }
        try {
            conn.close();
        } catch (SQLException e) {
            Log.error("---【error】关闭数据库连接异常,请检查数据,ActionNum:"+actionEntity.getActionNum());
            e.printStackTrace();
        }
    }
}
